<?php

class MY_New_Controller extends CI_Controller
{
    protected $_class_name;
    protected $_myModel;
    protected $_logsModel;
    protected $_method;
    protected $_directory;
    protected $_prefix_path;

    protected $_html_path;  //html目录

    protected $_dwt_list;
    protected $_dwt_info;
    protected $_dwt_info_modal;

    protected $_res = array('error' => 0, 'message' => '', 'content' => '', 'append' => '');

    protected $require_login = NULL;

    public $datas;
    public $_breadcrumb = array();

    /**
     * Constructor function
     * @todo Document more please.
     */
    public function __construct()
    {

        parent::__construct();
        //$this->check_privilege();

        $class_name        = $this->router->class;
        $this->_class_name = $class_name;
        $this->_method     = $this->router->method;
        $this->_directory  = rtrim($this->router->directory, '/');

        $this->_html_path = trim('html/' . $this->_directory . '/', '/') . '/';

        $subfolder          = empty($subfolder) ? $this->_directory : $subfolder;
        $this->_prefix_path = empty($subfolder) ? '' : $subfolder . '/';

        self::_init($class_name);

        // Start the timer for how long the request takes
        $this->_start_rtime = microtime(true);
        //$this->db->cache_off();
        //$this->load->config($config);
        //$this->load->library('format');
        //加载语言文件
        //$idiom = $this->session->get_userdata('language');
        // $this->lang->load('common', 'zh');

        // 加载日志记录模型
        // $this->load->model('logs_model');
        //  $this->_logsModel = $this->logs_model;
        //  if(@$_REQUEST['debug'] == 'ly'){
        //    		echo "<pre>";
        //    		print_r($_SERVER);
        //   		die();
        //  }
    }

    protected function _init($class_name)
    {
        $this->_dwt_list       = $this->_html_path . $class_name . '_list';
        $this->_dwt_info       = $this->_html_path . $class_name . '_info';
        $this->_dwt_info_modal = $this->_html_path . $class_name . '_modal.php';

        //page default variables
        $this->datas['my_router'] = $this->_directory . '/' . $class_name;
        $this->datas['my_class']  = $class_name;
        $this->datas['my_method'] = $this->_method;
        $this->datas['my_dir']    = $this->_directory;
        $this->datas['full_page'] = TRUE;

        $this->_res['interface'] = $class_name . '/' . $this->_method;

        //check login
        //	$this->_check_privilege();

        //load models
        $this->load_model($class_name . '_model', TRUE);

        //initial pager
        $this->_init_pager();
        //breadcrumb
        $this->_load_breadcrumb();
    }

    /**
     * 接收ajax请求
     * @param unknown $action
     * @param number $item_id
     */
    public function ajax($action, $item_id = 0)
    {
        $datas            = $this->input->get();
        $datas['item_id'] = $item_id;
        $this->process_ajax($action, $datas);
    }

    public function load_model($model, $self_model = FALSE)
    {
        $myModel         = $model;
        $model_base_path = APPPATH . 'models/' . $this->_prefix_path;
        if (file_exists($model_base_path . $model . '.php') ||
            file_exists($model_base_path . ucfirst($model) . '.php')
        ) {
            $model = $this->_prefix_path . $model;
        } else {
            $model_base_path = APPPATH . 'models/';
            if (!file_exists($model_base_path . $model . '.php') &&
                !file_exists($model_base_path . ucfirst($model) . '.php')
            ) {
                $model = NULL;
            }
        }
        if ($model != NULL) {
            $this->load->model($model);
            if ($self_model) {
                $this->_myModel = $this->$myModel;
            }
        } else {
            $this->load->model('my_ci_model');
            if ($self_model) {
                $this->_myModel = $this->my_ci_model;
            }
        }
    }

    private function _init_pager()
    {
        $this->datas['pager'] = $this->_myModel->page_and_size(array('page' => 0));
    }

    public function _load_breadcrumb()
    {
        $breadcrumb = array();
        if (!empty($this->datas['page_title'])) {
            $breadcrumb[] = array('title' => $this->datas['page_title'], 'type' => 'lable', 'class' => 'active');
        }
        $this->datas['breadcrumb'] = array_merge($breadcrumb, $this->_breadcrumb);;
    }

    /**
     * 分页数据
     *
     * @param number $page
     */
    public function query_list($filter = array(), $page = 1, $load_page = TRUE)
    {
        $get = $this->input->get();
        if (!empty($get)) {
            $filter = array_merge($filter, $get);
        }
        if (isset($filter['page']) && $filter['page'] > 0) {
            $page = $filter['page'];
        }
        $item_list            = $this->_myModel->get_list($filter, $page);
        $this->datas['lists'] = $item_list['list'];
        $this->datas['pager'] = $item_list['pager'];

        if ($this->datas['full_page']) {
            $this->load->view($this->_dwt_list, $this->datas);
        } else {
            return $this->load->view($this->_dwt_list, $this->datas, TRUE);
        }
    }


    public function post($action = '')
    {
        $post = $this->input->post();
        $this->process_ajax($post['action'], $post);
    }

    protected function _do_request($requests = array())
    {
        $requests['debug'] = TRUE;
        die(json_encode($requests));
    }

    /**
     * 分页数据
     *
     * @param number $page
     */
    protected function _query_list($page = 1, $filter = array(), $load_page = TRUE)
    {
        $get = $this->input->get();
        if (!empty ($get)) {
            $filter = array_merge($filter, $get);
        }
        if (isset ($filter ['page']) && $filter ['page'] > 0) {
            $page = $filter ['page'];
        }
        $item_list = $this->_myModel->get_list($filter, $page);
        //print_r($item_list);die;
        $this->datas['lists'] = $item_list ['list'];
        $this->datas['pager'] = $item_list ['pager'];
        if ($this->datas['full_page']) {
            $this->load->view($this->_dwt_list, $this->datas);
        } else {
            return $this->load->view($this->_dwt_list, $this->datas, TRUE);
        }
    }

    protected function _make_res_error($message)
    {
        $this->_res['error']   = 1;
        $this->_res['message'] = $message;
        $this->_make_response();
    }

    // 权限检测开始
    function check_privilege()
    {
        $directory = $this->router->directory;
        $class     = $this->router->class;
        $method    = $this->router->method;

        $exclude_controller          = array();
        $exclude_controller[]        = 'privilege';
        $exclude_method['privilege'] = array('signin', 'logout', 'admin_authorize');

        $is_process = TRUE;
        if (in_array($class, $exclude_controller)) {
            $is_process = FALSE;
        }
        if (isset($exclude_method[$class]) && !in_array($method, $exclude_method[$class])) {
            $is_process = FALSE;
        }
        //防止重复登录，如果已登录状态再次进入登录页面则直接进入首页
        if ($method == 'signin' && !$this->check_session()) {
            redirect('./');
        }

        if ($is_process && $this->check_session()) {
            $go_login = TRUE;
            //判断是否自动登录
            $autoLogin = $this->input->cookie('lcikp_si', TRUE);
            $autoLogin = 0; //关闭自动登录
            if ($autoLogin > 0) {
                $this->load->model('privilege_model');
                $go_login = $this->privilege_model->cookie_auto_login();
            }
            if ($go_login) {
                $this->access_deny();
            }
        }
        if (!empty($_SESSION['sid']) && $_SESSION['sid'] != session_id()) {
            $this->load->model('privilege_model');
            $update_datas['last_session'] = session_id();
            $this->privilege_model->edit_data($update_datas, $_SESSION['admin_id']);
            $_SESSION['sid'] = $update_datas['last_session'];
        }
    }

    function access_deny($message = '')
    {
        $redirect_url = 'privilege/signin';
        $is_ajax      = intval($this->input->is_ajax_request());
        if ($this->router->class != $this->router->default_controller && !$is_ajax) {
            $redirect_url .= '/?redirect=' . rawurlencode(site_url($this->router->uri->uri_string));
        }
        $message = empty($message) ? '登录超时！请重新登录！' : $message;
        if ($is_ajax > 0) {
            make_json_error($message, array('redirect' => site_url($redirect_url)));
        } else {
            $links = array('text' => "返回登录", 'href' => $redirect_url);
            show_message($message, $links, 'error');
        }
    }

    // 权限检测结束

    function check_session()
    {
        return (empty($_SESSION['admin_id']));
    }


    /**
     * Destructor function
     * @author Chris Kacerguis
     */
    public function __destruct()
    {
        // Record the "stop" time of the request
        $this->_end_rtime = microtime(true);

    }
}